package com.appbee.gdata.youtube.client.presenter;

import javax.inject.Inject;

import com.appbee.core.client.jsni.JsArrayConverter;
import com.appbee.core.client.rpcfilter.RpcFilterChain;
import com.appbee.core.client.rpcfilter.callback.FilterCallback;
import com.appbee.core.client.rpcfilter.chain.ChainBuilder;
import com.appbee.core.client.ui.ISimpleFilterView;
import com.appbee.gdata.youtube.client.search.Entry;
import com.appbee.gdata.youtube.client.search.Feed;
import com.appbee.gdata.youtube.client.search.FeedCallback;
import com.appbee.gdata.youtube.client.search.FeedResult;
import com.appbee.gdata.youtube.client.search.YoutubeFilter;
import com.appbee.gdata.youtube.client.search.YoutubeService;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;

public class YoutubeDataProvider extends AsyncDataProvider<Entry> implements
		RpcFilterChain<YoutubeFilter, FeedResult>
{
	private YoutubeService service;
	private RpcFilterChain<YoutubeFilter, FeedResult> rpcFilter;
	private ISimpleFilterView filterView;
	
	@Inject
	public YoutubeDataProvider(YoutubeService service)
	{
		super();
		this.service = service;
		rpcFilter = new ChainBuilder<YoutubeFilter, FeedResult>()
				.chainMinLength(1)
				.chainCache(60, 100)
				.chainMonoSync()
				.chainLast(this);
	}

	public ISimpleFilterView getFilterView()
	{
		return filterView;
	}

	public void setFilterView(ISimpleFilterView filterView)
	{
		this.filterView = filterView;
	}

	@Override
	public void doFilter(YoutubeFilter filter,
			final FilterCallback<FeedResult> callback)
	{
		service.findByFilter(filter, new FeedCallback()
		{
			
			@Override
			public void onSuccess(FeedResult result)
			{
				callback.onSuccess(result);
			}
			
			@Override
			public void onFailure(Throwable caught)
			{
				Window.alert(caught.getMessage());
			}
		});
	}

	@Override
	protected void onRangeChanged(HasData<Entry> display)
	{
		if (filterView.getSearchValue().length() == 0)
			return;

		final Range range = display.getVisibleRange();
		YoutubeFilter filter = new YoutubeFilter();
		filter.setQuery(filterView.getSearchValue());
		filter.setMaxResult(range.getLength());
		filter.setStartIndex(range.getStart() + 1);
		rpcFilter.doFilter(filter, new FilterCallback<FeedResult>()
		{

			@Override
			public void onSuccess(FeedResult feedResult)
			{
				Feed feed = feedResult.getFeed();
				updateRowCount(feed.getOpenSearchTotalResults(), false);
				updateRowData(range.getStart(),
						JsArrayConverter.toList(feed.getEntry()));

			}

		});
	}


}
